package com.tianlh.zookeeper;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.CountDownLatch;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;

/**
 * @author 黑子
 * @Date 2018/1/10 13:02
 */
public class ZkLock {

    static String path = "/lock_path";
    static RetryPolicy retry = new ExponentialBackoffRetry(1000, 3);
    static CuratorFramework client = CuratorFrameworkFactory.builder().connectString("127.0.0.1:2181")
        .namespace("master").sessionTimeoutMs(5000).retryPolicy(retry).build();

    public static void main(String[] args) {
        client.start();
        final InterProcessMutex lock = new InterProcessMutex(client, path);
        final CountDownLatch down = new CountDownLatch(1);

        for(int i=0; i<20; ++i){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        down.await();
                        lock.acquire();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss|SSS");
                    String orderId = format.format(new Date());
                    System.out.println("生成的订单号: " + orderId);
                    try {
                        lock.release();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }, "Thread"+i).start();
        }
        // 线程创建完统一开始
        down.countDown();
    }
}
